use serde_json::Value;

/// 市场条件定义
#[derive(Debug, Clone)]
pub struct MarketConditions {
    pub inflation_rate: f64,
    pub interest_rate: f64,
    pub regulation_level: f64,
    pub demand_level: f64,
    pub external_factors: Value,
}

impl MarketConditions {
    /// 创建默认市场条件
    pub fn new() -> Self {
        MarketConditions {
            inflation_rate: 0.02,
            interest_rate: 0.05,
            regulation_level: 0.3,
            demand_level: 0.7,
            external_factors: Value::Null,
        }
    }

    /// 更新市场条件
    pub fn update(&mut self, new_conditions: &Value) {
        if let Some(inflation) = new_conditions.get("inflation_rate").and_then(|v| v.as_f64()) {
            self.inflation_rate = inflation;
        }
        if let Some(interest) = new_conditions.get("interest_rate").and_then(|v| v.as_f64()) {
            self.interest_rate = interest;
        }
        if let Some(regulation) = new_conditions.get("regulation_level").and_then(|v| v.as_f64()) {
            self.regulation_level = regulation;
        }
        if let Some(demand) = new_conditions.get("demand_level").and_then(|v| v.as_f64()) {
            self.demand_level = demand;
        }
        self.external_factors = new_conditions.get("external_factors")
            .cloned()
            .unwrap_or(Value::Null);
    }

    /// 评估市场稳定性
    pub fn stability_score(&self) -> f64 {
        let mut score = 1.0;
        score -= self.inflation_rate.abs();
        score -= (self.interest_rate - 0.05).abs() / 2.0;
        score += self.demand_level / 2.0;
        score -= self.regulation_level / 3.0;
        score.max(0.0)
    }
}